package com.example.demo.controller;
import com.example.demo.pojo.User;
import com.example.demo.repository.UserRepository;
import com.example.demo.service.UserService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.ui.Model;

@Controller
public class LoginController {
    @Autowired
    private UserService userService;

    // 显示登录页面
    @GetMapping("/login")
    public String showLoginPage() {
        return "redirect:/login/login.html"; // 重定向到静态页面
    }
    // 处理登录请求
    @PostMapping("/login")
    public String login(@RequestParam String username, @RequestParam String password, HttpSession session, Model model) {
        // 验证用户名和密码
        User user = userService.validateUser(username, password);
        if (user != null) {
            // 登录成功，将用户信息存储到会话中
            // user.setPassword(null); // 移除密码
            session.setAttribute("currentUser", user);

            // 输出日志信息
            System.out.println("用户登录成功: " + user.getUsername());
            System.out.println("会话ID: " + session.getId());
            User currentUser = (User) session.getAttribute("currentUser");
            System.out.println("Current User in /user-profile: " + currentUser);
            model.addAttribute("currentUser", currentUser);
            return "redirect:/anime"; // 登录成功，跳转到欢迎页面
        } else {
            System.out.println("登陆失败");
            return "redirect:/login/login.html?error=true"; // 登录失败，返回登录页面并显示错误
        }
    }
}

